//
//  UILabel+Nomal.m
//  CXDToolKit
//
//  Created by 陈小东 on 15/3/4.
//  Copyright (c) 2015年 ___cxd___. All rights reserved.
//

#import "UILabel+Nomal.h"
#import <objc/runtime.h>

@implementation UILabel (Nomal)
- (void)text:(NSString *)str color:(UIColor *)color font:(UIFont *)font{
    if (!str){
        str = self.text;
    }
    if (!color){
        color = self.textColor;
    }
    if (!font){
        font = self.font;
    }
    [self.attributeString setAttributes:@{NSForegroundColorAttributeName:color,
                                          NSFontAttributeName:font}
                                  range:[self.text rangeOfString:str]];
}

- (NSMutableAttributedString *)attributeString{
    NSMutableAttributedString *attributeString = objc_getAssociatedObject(self, _cmd);
    if (attributeString && [attributeString.string isEqualToString:self.text]) {
        return attributeString;
    }
    attributeString = [[NSMutableAttributedString alloc] initWithString:self.text];
    objc_setAssociatedObject(self, _cmd, attributeString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return attributeString;
}

- (CGSize)fitTextHeight{
    CGSize size=CGSizeMake(self.bounds.size.width, NSIntegerMax);
    return [self contentSizeWithSize:size];
}

- (CGSize)fitTextWidth{
    CGSize size=CGSizeMake( NSIntegerMax,self.bounds.size.height);
    return [self contentSizeWithSize:size];
}

- (CGSize)contentSizeWithSize:(CGSize)sizet{
#ifndef __IPHONE_7_0
#define __IPHONE_7_0     70000
#endif
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    if([[[UIDevice currentDevice] systemVersion] floatValue]<7.0){
        
        CGSize size = [self.text sizeWithFont:self.font constrainedToSize:sizet lineBreakMode:self.lineBreakMode];
        return size;
    }else{
        NSDictionary *attributes = @{NSFontAttributeName:self.font};
        CGSize contentSize = [self.text boundingRectWithSize:sizet
                                                     options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                  attributes:attributes
                                                     context:nil].size;
        return contentSize;
    }
#else
    NSDictionary *attributes = @{ NSFontAttributeName:self.font};
    CGSize contentSize = [self.text boundingRectWithSize:sizet
                                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                              attributes:attributes
                                                 context:nil].size;
    return contentSize;
#endif
}
@end
